﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using WapChargingSDK;
using System.Windows.Media.Imaging;

namespace NapThe
{
        public class NapTheDienThoaiController : Controller
        {
            public static bool isRunning = false;
            public static int currentAccount = 0;
            public static int counter = 0;
            public static string tbMaSo = "";
            public static string tbSeri = "";
            public static string testNapthe;
            public static IGamePage igame=null;
            //public void OnMessageBoxAction(IAsyncResult ar)
            //{
            //}

            public override void process(INapTheDienThoai p)
            {
                p.setRectangle1(0);
                p.setTextBlock("textBlock8", "");
                counter = 0;
                string t1 = p.getMaSo();
                string t2 = p.getSeri();
                string iss = "VT";
                if (!(p.getRadio("1") ||
                    p.getRadio("2") ||
                    p.getRadio("3")))
                {
                    Report.contentOfMessage = "Bạn phải chọn loại thẻ cào";
                    isRunning = false;
                    p.navigateWhenFailed();
                    return;
                }
                else
                {
                    if (p.getRadio("1"))
                    {
                        iss = "VINA";
                    }
                    if (p.getRadio("2"))
                    {
                        iss = "MOBI";
                    }
                }

                if (spaceExits(t1))
                {
                    Report.contentOfMessage = "Mã số không được chứa khoảng trắng!";
                    p.navigateWhenFailed();
                    return;
                }

                if (!isNumber(t1))
                {
                    Report.contentOfMessage = "Mã số thẻ cào chỉ chứa con số";
                    p.navigateWhenFailed();
                    return;
                }

                if (spaceExits(t2))
                {
                    Report.contentOfMessage = "Số Seri không được chứa khoảng trắng!";
                    p.navigateWhenFailed();
                    return;
                }

                if (!isNumberOrChar(t2))
                {
                    Report.contentOfMessage = "Số Seri chỉ chứa con số hoặc chữ cái";
                    p.navigateWhenFailed();
                    return;
                }

                if (t1.Length < 12 || t1.Length > 14)
                {
                    Report.contentOfMessage = "Mã số thẻ cào phải dài 12 đến 14 chữ số!";
                    p.navigateWhenFailed();
                    return;
                }
                if (t2.Length < 9 || t2.Length > 15)
                {
                    Report.contentOfMessage = "Số Seri phải dài từ 9 đến 15 ký tự!";
                    p.navigateWhenFailed();
                    return;
                }

                ServiceController s1 = new ServiceController();
                ServiceController.sent = false;
                t1 = t1.ToUpper();
                t2 = t2.ToUpper();

                if (s1.enableProcess("Wrong1.txt", "Timer1.txt"))
                {
                    WebClient proxy = new WebClient();
                    p.processTimer("Start");

                    proxy.DownloadStringCompleted += (sender, e) =>
                    {
                        counter = 0;
                        p.processTimer("Stop");

                        if (e.Error == null)
                        {
                            //Process the result...
                            //p.textBlock8.Text = "100% completed";
                            p.setTextBlock("textBlock8", "100% completed");
                            //p.rectangle1.Width = (double)(4 * 183);
                            p.setRectangle1((double)(4 * 183));
                            string data = e.Result;
                            //data = "   001|Kiem tra thanh cong | 10000 ";
                            ServiceController s = ServiceController.get(data);
                            ServiceController.sent = true;
                            string t = s.show();
                            Report.contentOfMessage = t;
                            napTheDienThoai(s, p, data);
                            isRunning = false;
                            
                        }
                        else
                        {
                            Report.contentOfMessage = "Không truy cập được vào mạng Internet!";
                            isRunning = false;
                            counter = 0;
                            p.navigateWhenFailed();

                        }
                    };
                    t2 = t2.ToUpper();
                    t1 = t1.ToUpper();
                    string nocache = DateTime.Now.ToLongTimeString();

                    isRunning = true;
                    string[] card = getCardLink();

                    string noCache = DateTime.Now.ToLongTimeString();
                    proxy.DownloadStringAsync(new Uri(card[0] + iss
                                    + card[1] + t2
                                    + card[2] + t1
                                    + card[3]
                                    + card[4]
                                    + card[5]
                        //+ card[6] + 
                                    + "&t=" + noCache
                        , UriKind.Absolute));

                }
                else
                {
                    //MessageBox.Show("Bạn đã nhập sai 3 lần, xin hãy đợi đủ 30 phút!");
                    //MessageBox.Show(ServiceController.x);
                    //Guide.BeginShowMessageBox(" ",
                    Report.contentOfMessage = ServiceController.x;
                    //        new string[] { "OK" },
                    //        0, MessageBoxIcon.None,
                    //        new AsyncCallback(OnMessageBoxAction), null);
                    isRunning = false;
                    p.navigateWhenFailed();
                }
                return;
            }

            public void napTheDienThoai(ServiceController s, INapTheDienThoai p, string data)
            {
                bool x = s.enableProcess("Wrong1.txt", "Timer1.txt");

                if (s is Service01)
                {
                    x = ServiceController.isFinish(data);
                    storeMoney(ServiceController.x);
                    if (p != null)
                    {
                        //p.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.RelativeOrAbsolute));
                        p.navigateWhenFailed();
                        
                    }
                    ServiceController.x = ServiceController.getMessage(data);
                    
                }
                else
                {
                    if (p != null)
                    {
                        p.navigateWhenFailed();
                    }
                }
            }

            public override void process(IGamePage p)
            {
                bool duTien = false;
                if (!isFree())
                {
                    bool truTienTrongTaiKhoan = false;
                    currentAccount = 0;
                    if (isEnoughMoney(truTienTrongTaiKhoan, 300))
                    {
                        duTien = true;
                    }
                    if (duTien || currentAccount == 0)
                    {
                        testNapthe = currentAccount.ToString();
                        p.setTextBlock5( currentAccount.ToString());
                        
                        currentAccount = 0;
                    }
                }
                else
                {
                    MessageBox.Show("xu la null");
                    p.setTextBlock5("");
                }

            }

           
            public static bool isFree()
            {
                bool free = false;
                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                if (storage.FileExists("A\\Property.txt"))
                {
                    IsolatedStorageFileStream fileStream = storage.OpenFile("A\\Property.txt", FileMode.Open, FileAccess.Read);
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        string myString = reader.ReadLine();
                        myString = Decrypt(myString,
                            "aspecth283sh48jd92p0q941hn281c0b47j32m6",
                            "nak34mk96th15hu1");

                        if (myString.Equals("FREE"))
                        {
                            free = true;
                        }

                        reader.Close();
                        reader.Dispose();
                    }
                    fileStream.Close();
                    fileStream.Dispose();
                    //MessageBox.Show(myString);
                }

                storage.Dispose();
                return free;
            }

            
            // tien ban dau

            public static int numberOfMoney(IsolatedStorageFile storage)
            {
                int currMoney = 3000;
                string myString = "";
                if (storage.FileExists("Money.txt"))
                {
                    IsolatedStorageFileStream fileStream = storage.OpenFile("Money.txt", FileMode.Open,
                         FileAccess.Read, FileShare.Read /*, 
                    FileAccess.Read*/);
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        myString = reader.ReadLine();
                        myString = removeFirst(myString);
                        myString = Decrypt(myString,
                            "bkth83sh48jd92pq94hn81c0b47j32m6",
                            "5t93v31hg5yg9hs");
                        currMoney = Int32.Parse(myString);
                        
                        reader.Close();
                        reader.Dispose();
                    }
                    fileStream.Close();
                    fileStream.Dispose();
                }
                return currMoney;
            }

            public bool isEnoughMoney(bool truTienTrongTaiKhoan, int subtract)
            {
                bool enough = false;
                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                int currMoney = 3000;
                string myString = "";
                currMoney = numberOfMoney(storage);

                if (truTienTrongTaiKhoan)
                {
                    currMoney -= subtract; // 300;
                }

                myString = "" + currMoney;
                if (currMoney == 0 && truTienTrongTaiKhoan)
                {
                    enough = true;
                }
                if (currMoney > 0)
                {
                    enough = true;
                }
                else
                {
                    currMoney = 0;
                }
                currentAccount = currMoney;

                if (truTienTrongTaiKhoan)
                {
                    FileStream stream = storage.OpenFile("Money.txt", FileMode.Create); // Open a file in Create mode
                    BinaryWriter writer = new BinaryWriter(stream);

                    myString = Encrypt(myString,
                                "bkth83sh48jd92pq94hn81c0b47j32m6",
                                "5t93v31hg5yg9hs");
                    writer.Write(myString);
                    writer.Close();
                    writer.Dispose();
                    stream.Close();
                    stream.Dispose();
                }

                storage.Dispose();
                return enough;
            }

            public void storeMoney(string money)
            {
                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                int addMoney = Int32.Parse(parse(money));
                addMoney = ServiceController.getXu(addMoney);
                //MessageBox.Show("Xu: " + addMoney); 
                int finalMoney = addMoney;
                string myString = "";

                if (storage.FileExists("Money.txt"))
                {
                    IsolatedStorageFileStream fileStream = storage.OpenFile("Money.txt", FileMode.Open,
                        FileAccess.Read, FileShare.Read /*, 
                    FileAccess.Read*/);
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        myString = reader.ReadLine();
                        myString = removeFirst(myString);
                        myString = Decrypt(myString,
                            "bkth83sh48jd92pq94hn81c0b47j32m6",
                            "5t93v31hg5yg9hs");
                        int currMoney = Int32.Parse(parse(myString));

                        finalMoney = currMoney + addMoney;
                        Controller.showAddedMoney(finalMoney, addMoney);
                        //if (Model.Material.m != null)
                        //{
                        //    Model.Material.m.currentMoney = finalMoney;
                        //}
                       

                        reader.Close();
                        reader.Dispose();
                    }
                    fileStream.Close();
                    fileStream.Dispose();
                    //MessageBox.Show(myString);
                }
                else
                {
                    finalMoney += 3000;
                }

                myString = "" + finalMoney;

                FileStream stream = storage.OpenFile("Money.txt", FileMode.Create); // Open a file in Create mode
                BinaryWriter writer = new BinaryWriter(stream);
                myString = Encrypt(myString,
                            "bkth83sh48jd92pq94hn81c0b47j32m6",
                            "5t93v31hg5yg9hs");
                writer.Write(myString);
                writer.Close();
                writer.Dispose();
                stream.Close();
                stream.Dispose();

                if (storage.FileExists("Timer1.txt"))
                {
                    storage.DeleteFile("Timer1.txt");
                }

                if (storage.FileExists("Wrong1.txt"))
                {
                    storage.DeleteFile("Wrong1.txt");
                }

                storage.Dispose();


                //MessageBox.Show(myString);
            }

            private static string removeFirst(string t)
            {
                return t.Substring(1);
            }

            private string parse(string x)
            {
                string t = "";
                char[] array = x.ToCharArray();
                for (int i = 0; i < array.Length; i++)
                {
                    if (array[i] >= '0' && array[i] <= '9')
                    {
                        t = t + array[i];
                    }
                }

                return t;
            }

            public static string Encrypt(string dataToEncrypt, string password, string salt)
            {
                AesManaged aes = null;
                MemoryStream memStream = null;
                CryptoStream crStream = null;

                try
                {
                    //Generate a key based on a password and salt 
                    Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password,
                       Encoding.UTF8.GetBytes(salt));
                    //Create AES algorithm with 256-bit key and 128-bit block size  
                    aes = new AesManaged();
                    aes.Key = rfc2898.GetBytes(aes.KeySize / 8);
                    aes.IV = rfc2898.GetBytes(aes.BlockSize / 8);
                    memStream = new MemoryStream();
                    crStream = new CryptoStream(memStream, aes.CreateEncryptor(),
                       CryptoStreamMode.Write);

                    byte[] data = Encoding.UTF8.GetBytes(dataToEncrypt);
                    crStream.Write(data, 0, data.Length);
                    crStream.FlushFinalBlock();

                    //Return base-64 string  
                    return Convert.ToBase64String(memStream.ToArray());
                }
                finally
                {
                    //cleanup 
                    if (crStream != null)
                        crStream.Close();

                    if (memStream != null)
                        memStream.Close(); if (aes != null)
                        aes.Clear();
                }
            }

            public static string Decrypt(string dataToDecrypt, string password, string salt)
            {
                AesManaged aes = null;
                MemoryStream memStream = null;
                CryptoStream crStream = null;

                
                try
                {
                    Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password,
               Encoding.UTF8.GetBytes(salt));
                    aes = new AesManaged();
                    aes.Key = rfc2898.GetBytes(aes.KeySize / 8);
                    aes.IV = rfc2898.GetBytes(aes.BlockSize / 8);

                    memStream = new MemoryStream();
                    crStream = new CryptoStream(memStream, aes.CreateDecryptor(),
                       CryptoStreamMode.Write);
                    byte[] data = Convert.FromBase64String(dataToDecrypt);
                    crStream.Write(data, 0, data.Length);
                    crStream.FlushFinalBlock();

                    byte[] decryptBytes = memStream.ToArray();
                    return Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
                }
                finally
                {
                    if (crStream != null)
                        crStream.Close();

                    if (memStream != null)
                        memStream.Close();

                    if (aes != null)
                        aes.Clear();
                }
            }

            private bool spaceExits(string t)
            {
                bool found = false;
                int i = 0;
                while (!found && i < t.Length)
                {
                    if (t[i] == ' ')
                    {
                        found = true;
                    }
                    i++;
                }
                return found;
            }

            private bool isNumberOrChar(string t)
            {
                bool found = true;
                int i = 0;
                char[] t1 = t.ToCharArray();
                while (i < t.Length && found)
                {
                    if (t1[i] == '`' || t1[i] == '~' || t1[i] == '!' || t1[i] == '@' ||
                        t1[i] == '#' || t1[i] == '$' || t1[i] == '%' || t1[i] == '^' ||
                        t1[i] == '&' || t1[i] == '*' || t1[i] == '(' || t1[i] == ')' ||
                        t1[i] == '-' || t1[i] == '_' || t1[i] == '+' || t1[i] == '=' ||
                        t1[i] == '|' || t1[i] == '{' || t1[i] == '}' || t1[i] == ']' ||
                        t1[i] == '[' || t1[i] == '\\' || t1[i] == ';' || t1[i] == ':' ||
                        t1[i] == '"' || t1[i] == '\'' || t1[i] == '?' || t1[i] == '/' ||
                        t1[i] == '.' || t1[i] == ',' || t1[i] == '>' || t1[i] == '<'
                        )
                    {
                        found = false;
                    }
                    i++;
                }

                return found;
            }

            private bool isNumber(string t)
            {
                bool found = true;
                int i = 0;
                char[] t1 = t.ToCharArray();
                while (i < t.Length && found)
                {
                    if (t1[i] < '0' || t1[i] > '9')
                    {
                        found = false;
                    }
                    i++;
                }

                return found;
            }
            public bool CheckMoney(int checkMoney)
            {
                bool napTien = false;
                if (!isFree())
                {
                    //if (!isEnoughMoney(truTienTrongTaiKhoan, 300))
                    //{
                    //    napTien = true;
                    //}
                    IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                    int currMoney = 3000;
                    //string myString = "";
                    currMoney = numberOfMoney(storage);
                    storage.Dispose();
                    if (currMoney < checkMoney)
                    {
                        napTien = true;
                    }
                }
                return napTien;
                
            }

            private static string[] getCardLink()
            {
                string[] x = new string[6];
                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                if (storage.FileExists("A\\Card.txt"))
                {
                    IsolatedStorageFileStream fileStream = storage.OpenFile("A\\Card.txt", FileMode.Open, FileAccess.Read);
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        x[0] = reader.ReadLine();
                        x[1] = reader.ReadLine();
                        x[2] = reader.ReadLine();
                        x[3] = reader.ReadLine();
                        x[4] = reader.ReadLine();
                        x[5] = reader.ReadLine();
                        //x[6] = reader.ReadLine();
                        reader.Close();
                        reader.Dispose();
                    }
                    fileStream.Close();
                    fileStream.Dispose();
                }
                storage.Dispose();

                return x;
            }

            public void setTypeOfTheDienThoai(object sender)
            {
                RadioButton radio = (RadioButton)sender;
                if (radio.Name.Equals("radioButton1"))
                {
                   NapTheDienThoaiModel.intNhaMang = 1;
                   return;
                }
                if (radio.Name.Equals("radioButton2"))
                {
                    NapTheDienThoaiModel.intNhaMang = 2;
                    return;
                }
                if (radio.Name.Equals("radioButton3"))
                {
                    NapTheDienThoaiModel.intNhaMang = 3;
                    return;
                }


            }
        }

}
